package com.jane.addressbook.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		HttpSession session = req.getSession(true);
		
		String uid = (String)session.getAttribute("uid");
		
		String url = req.getRequestURI();
		
		String contextPath = req.getContextPath();
		System.out.println("url -> " + url + ", context -> " + contextPath);
		if (url.equals(contextPath) || url.equals(contextPath + "/index.jsp") || url.equals(contextPath + "/login")) {
			chain.doFilter(req,resp);
			return;
		}
		
		if(uid == null || "".equals(uid)){
			String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+"/";
			System.out.println(basePath);
			resp.sendRedirect(basePath+"index.jsp");
			chain.doFilter(req,resp);
		}
		else{
			System.out.println("uid -> " + uid + " can access the web.");
			chain.doFilter(req,resp);
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
